<script setup lang="ts">
import type { PropType } from 'vue';
import type { UserBO, UserRoleItem } from '@/model/UserRoleBo';
import {
  ElDialog,
  ElMessage,
} from 'element-plus-cisdi';
import { computed, ref, watch } from 'vue';
import { UserTableColProp } from '@/constants/UserManage';
import { t } from '@/locales';
import { formatTimestampToLocalDateString } from '@/utils/TimeFormatUtil';
// 接收props
const props = defineProps({
  // 外部传入的用户数据和角色列表（格式：key:value;key2:value2）
  user: {
    type: Object as PropType<UserBO>,
    default: () => ({}),
  },
  // 某用户的角色列表
  rolesList: {
    type: Array,
    default: () => [],
  },
  // 全部的角色列表
  fullRolesList: {
    type: Array,
    default: () => [],
  },
  pageData: {
    type: Object,
    default: () => ({}),
  },
  fullRolePageInfo: {
    type: Object,
    default: () => ({}),
  },
  rolesVisible: {
    type: Boolean,
    default: false,
  },
  getRoleList: {
    type: Function,
    default: () => ({}),
  },
  getAssignableRoleList: {
    type: Function,
    default: () => ({}),
  },
});

const emit = defineEmits(['cancel', 'save', 'fetchAssignRoleList', 'deleteAssignRole', 'fetchFullAssignRoleList', 'addAssignRole']);

// 选中的用户角色数据
const roleSelection = ref<any[]>([]);

// 选中的全部角色数据
const fullRoleSelection = ref<any[]>([]);

// 展示的角色列表
const displayRoleDate = ref<any[]>(props.rolesList);

// 新增 弹窗可视状态
const addRoleVisible = ref(false);

// const userData = computed(() => props.user);
const userStatus = computed(() => props.user.status);

// 分页数据
const pageData = ref(props.pageData);

const fullRolePageInfo = ref(props.fullRolePageInfo);

const rolesVisible = computed(() => props.rolesVisible);

watch(() => props.rolesList, (newValue) => {
  displayRoleDate.value = newValue;
}, { immediate: false });

watch(() => props.pageData, (newValue) => {
  pageData.value = newValue;
}, { immediate: false });

watch(() => props.fullRolePageInfo, (newValue) => {
  fullRolePageInfo.value = newValue;
}, { immediate: false });

/**
 * 选择行变化
 * @param selection
 */
function handleSelectionChange(selection: any) {
  roleSelection.value = selection;
}

/**
 * 全部角色列表的选择行变化
 * @param selection
 */
function handleFullSelectionChange(selection: any) {
  fullRoleSelection.value = selection;
}

/**
 * 删除角色
 */
function deleteRoles() {
  if (roleSelection.value.length === 0) {
    ElMessage.warning('请至少选择一条数据');
    return;
  }
  try {
    // 传参使用roleSelection.value
    // 模拟 API 请求
    // const res = await api.post(`/org/mappings/${orgCode}`);
    const ids: number[] = roleSelection.value.map(role => role.id);
    // displayRoleDate.value = displayRoleDate.value.filter(role =>
    //   !roleSelection.value.some(selected =>
    //     selected.roleCode === role.roleCode,
    //   ),
    // )
    emit('deleteAssignRole', { ids });
  } catch (error) {
    console.error('删除角色失败:', error);
  }
}

function deleteRole(row: any) {
  // displayRoleDate.value = displayRoleDate.value.filter(role => role.roleId !== row.roleId)
  emit('deleteAssignRole', { ids: [row.id] });
}

async function handleRoles() {
  await props.getAssignableRoleList({
    orgCode: props.user.orgCode,
    current: 1,
    size: 10,
    userId: props.user.userId,
  });

  addRoleVisible.value = true;
}

/**
 * 新增角色
 */
function addRoles() {
  if (fullRoleSelection.value.length === 0) {
    ElMessage.warning('请至少选择一条数据');
    return;
  }
  try {
    // 传参使用roleSelection.value
    // 模拟 API 请求
    // const res = await api.post(`/org/mappings/${orgCode}`);
    const list: UserRoleItem[] = [];
    fullRoleSelection.value.forEach((selected) => {
      list.push({
        roleId: selected.roleId,
        roleCode: selected.roleCode,
        roleOrgCode: selected.roleOrgCode,
      });
      // if (!displayRoleDate.value.some(role => role.roleCode === selected.roleCode)) {
      //   displayRoleDate.value.push(selected)
      // }
    });

    const data = {
      userId: props.user.userId,
      roles: list,
    };
    emit('addAssignRole', data);
    addRoleVisible.value = false;
  } catch (error) {
    console.error('新增角色失败:', error);
  }
}

// 保存数据
// function handleSave() {
//   const result = displayRoleDate.value
//   emit('save', result)
// }

function handleSizeChange(val: number) {
  pageData.value.size = val;
  emit('fetchAssignRoleList', { ...pageData.value });
}

function handleCurrentChange(val: number) {
  pageData.value.current = val;
  emit('fetchAssignRoleList', { ...pageData.value });
}

function handleFullSizeChange(val: number) {
  fullRolePageInfo.value.size = val;
  emit('fetchFullAssignRoleList', { ...fullRolePageInfo.value });
}

function handleFullCurrentChange(val: number) {
  fullRolePageInfo.value.current = val;
  emit('fetchFullAssignRoleList', { ...fullRolePageInfo.value });
}
const activeTab = ref<string>('info');
const sidebarItems = [
  { id: 'info', name: t('userRole.baseInfo') },
  { id: 'role', name: t('userRole.roleList') },
];
</script>

<template>
  <ElDialog v-model="rolesVisible" class="responsive-dialog" body-class="extend-info-body" :title="t('user.assignRoles')" @close="$emit('cancel')">
    <div class="extend-info-modal">
      <!-- 左侧导航 -->
      <div class="dialog-sidebar">
        <div
          v-for="item in sidebarItems"
          :key="item.id"
          class="sidebar-item"
          :class="{ active: activeTab === item.id }"
          @click="activeTab = item.id"
        >
          <span>{{ item.name }}</span>
        </div>
      </div>
      <div class="extend-info-modal-right">
        <div class="extend-info-modal-right-title">
          {{ activeTab === 'info' ? t('userRole.baseInfo') : t('userRole.roleList') }}
        </div>
        <!-- 基本信息 -->
        <div v-show="activeTab === 'info'" class="extend-info-modal-right-base">
          <ElForm :model="user" label-width="110px">
            <ElRow :gutter="24">
              <ElCol :span="12">
                <ElFormItem label="用户编号" label-position="top">
                  <span class="form-value-item">{{ user.userId }}</span>
                </ElFormItem>
              </ElCol>
              <ElCol :span="12">
                <ElFormItem label="用户名称" label-position="top">
                  <span class="form-value-item">{{ user.userName }}</span>
                </ElFormItem>
              </ElCol>
            </ElRow>
            <ElRow :gutter="24">
              <ElCol :span="12">
                <ElFormItem label="组织机构代码" label-position="top">
                  <span class="form-value-item">{{ user.orgCode }}</span>
                </ElFormItem>
              </ElCol>
              <ElCol :span="12">
                <ElFormItem label="组织机构名称" label-position="top">
                  <span class="form-value-item">{{ user.orgFullName }}</span>
                </ElFormItem>
              </ElCol>
            </ElRow>
            <ElRow :gutter="24">
              <ElCol :span="12">
                <ElFormItem label="邮箱" label-position="top">
                  {{ user.email }}
                </ElFormItem>
              </ElCol>
              <ElCol :span="12">
                <ElFormItem label="状态" label-position="top">
                  <el-radio v-model="userStatus" disabled :label="1">
                    正常
                  </el-radio>
                  <el-radio v-model="userStatus" disabled :label="0">
                    停用
                  </el-radio>
                </ElFormItem>
              </ElCol>
            </ElRow>
            <ElRow :gutter="24">
              <ElCol :span="12">
                <ElFormItem label="创建人" label-position="top">
                  <span class="form-value-item">{{ user.createName }}</span>
                </ElFormItem>
              </ElCol>
              <ElCol :span="12">
                <ElFormItem label="创建时间" label-position="top">
                  <span class="form-value-item">{{ formatTimestampToLocalDateString(user.createTime) }}</span>
                </ElFormItem>
              </ElCol>
            </ElRow>
            <ElRow :gutter="24">
              <ElCol :span="12">
                <ElFormItem label="更新人" label-position="top">
                  <span class="form-value-item">{{ user.updateName }}</span>
                </ElFormItem>
              </ElCol>
              <ElCol :span="12">
                <ElFormItem label="更新时间" label-position="top">
                  <span class="form-value-item">{{ formatTimestampToLocalDateString(user.updateTime) }}</span>
                </ElFormItem>
              </ElCol>
            </ElRow>
          </ElForm>
        </div>
        <!-- 角色列表 -->
        <div v-show="activeTab === 'role'" class="extend-info-modal-right-role">
          <div class="extend-info-modal-right-role-action">
            <div class="mapping-operation">
              <ElButton type="danger" plain @click="deleteRoles">
                <span>{{ t('userRole.delete') }}</span>
              </ElButton>
              <ElButton class="button-border" @click="handleRoles">
                <span class="button-font">{{ t('userRole.add') }}</span>
              </ElButton>
            </div>
          </div>
          <ElTable
            :data="displayRoleDate" style="width: 100%; height: calc(100% - 60px);" header-cell-class-name="table-header"
            @selection-change="handleSelectionChange"
          >
            <ElTableColumn type="selection" width="55" align="center" />
            <ElTableColumn fixed="left" :label="t('userRole.index')" width="60" align="center">
              <template #default="scope">
                {{ scope.$index + 1 }}
              </template>
            </ElTableColumn>
            <ElTableColumn :show-overflow-tooltip="true" :prop="UserTableColProp.STATUS" :label="t('userRole.roleCode')" width="150" />
            <ElTableColumn :show-overflow-tooltip="true" :prop="UserTableColProp.ROLE_NAME" :label="t('userRole.roleName')" width="120" />
            <ElTableColumn :show-overflow-tooltip="true" :prop="UserTableColProp.DESCRIPTION" :label="t('userRole.permissionDesc')" width="150" />
            <ElTableColumn :show-overflow-tooltip="true" :prop="UserTableColProp.INHERITED_ROLE_NAME" :label="t('userRole.inheritedFrom')" width="120" />
            <ElTableColumn :show-overflow-tooltip="true" :prop="UserTableColProp.CREATE_NAME" :label="t('userRole.assigner')" width="150" />
            <ElTableColumn :show-overflow-tooltip="true" :prop="UserTableColProp.CREATE_TIME" :label="t('userRole.assignTime')" width="210">
              <template #default="scope">
                {{ scope.row.createTime ? formatTimestampToLocalDateString(scope.row.createTime) : null }}
              </template>
            </ElTableColumn>
            <ElTableColumn
              :show-overflow-tooltip="true" :prop="UserTableColProp.OPERATE" :label="t('userRole.operation')" width="100" align="center"
              fixed="right"
            >
              <template #default="scope">
                <ElPopconfirm :title="t('userRole.confirmDelete')" @confirm="deleteRole(scope.row)">
                  <template #reference>
                    <ElLink :underline="false" type="danger">
                      {{ t('userRole.delete') }}
                    </ElLink>
                  </template>
                </ElPopconfirm>
              </template>
            </ElTableColumn>
            <template #empty>
              <ElEmpty :image-size="62" />
            </template>
          </ElTable>
          <div class="page-data flex justify-end">
            <ElPagination
              :current-page="pageData.current" :page-size="pageData.size" :total="pageData.total"
              :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next, jumper" @current-change="handleCurrentChange"
              @size-change="handleSizeChange"
            />
          </div>
        </div>
      </div>
    </div>
  </ElDialog>

  <!-- 新增角色 -->
  <ElDialog v-model="addRoleVisible" destroy-on-close class="responsive-add-user-dialog" :title="t('userRole.addRole')" @close="addRoleVisible = false">
    <ElTable
      :data="fullRolesList" header-cell-class-name="table-header" style="width: 100%; height: 400px;"
      @selection-change="handleFullSelectionChange"
    >
      <ElTableColumn type="selection" width="55" align="center" />
      <ElTableColumn :prop="UserTableColProp.INDEX" :label="t('userRole.index')" width="60px" align="center">
        <template #default="scope">
          {{ scope.$index + 1 }}
        </template>
      </ElTableColumn>
      <ElTableColumn :show-overflow-tooltip="true" :prop="UserTableColProp.ROLE_CODE" :label="t('userRole.roleCode')" width="200" />
      <ElTableColumn :show-overflow-tooltip="true" :prop="UserTableColProp.ROLE_NAME" :label="t('userRole.roleName')" width="300" />
      <ElTableColumn :show-overflow-tooltip="true" :prop="UserTableColProp.DESCRIPTION" :label="t('userRole.permissionDesc')" width="320" />
      <ElTableColumn :show-overflow-tooltip="true" :prop="UserTableColProp.INHERITED_ROLE_NAME" :label="t('userRole.inheritedFrom')" width="200" />
    </ElTable>
    <div class="page-data">
      <ElPagination
        :current-page="fullRolePageInfo.current" :page-size="fullRolePageInfo.size"
        :total="fullRolePageInfo.total" :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next, jumper"
        @current-change="handleFullCurrentChange" @size-change="handleFullSizeChange"
      />
    </div>
    <template #footer>
      <div class="dialog-footer">
        <ElButton class="gray-button" @click="addRoleVisible = false">
          {{ t('userRole.cancel') }}
        </ElButton>
        <ElButton class="primary-button" @click="addRoles">
          {{ t('userRole.confirm') }}
        </ElButton>
      </div>
    </template>
  </ElDialog>
</template>

<style scoped lang="scss">
@use '@lingshu/theme-lib/scss/util.scss' as *;
:global(.el-dialog.responsive-dialog) {
  width: 1184px;
  height: 680px;
}
:global(.el-dialog.responsive-add-user-dialog) {
  width: 1184px;
  height: 600px;
}
:global(.extend-info-body) {
  padding-left: 0;
  padding-top: 0;
}
.extend-info-modal {
  width: 100%;
  height: 634px;
  background-color: useThemeVar('module_bg3');
  display: flex;
  flex-direction: row;
  .dialog-sidebar {
    width: 185px;
    border-right: 1px solid useThemeVar('border2');
    background-color: useThemeVar('module_bg2');
    padding: 20px 20px 0px 0;
  }

  .sidebar-item {
    padding: 9px 18px 9px 40px;
    cursor: pointer;
    transition: all 0.3s ease;
    display: flex;
    align-items: center;
    border-radius: 6px;
    position: relative; // 为伪元素定位做准备
    font-size: 14px;

    &:hover {
      background-color: #f5f7fa;
    }

    &.active {
      background-color: #ecf5ff;
      color: #409eff;
      border-radius: 8px; // 设置圆角

      // 使用 ::before 伪元素创建蓝色竖线
      &::before {
        content: '';
        position: absolute;
        left: 0;
        top: 50%;
        transform: translateY(-50%);
        width: 3px;
        height: 100%; // 竖线高度为内容的70%
        background-color: #409eff;
        border-radius: 0 2px 2px 0; // 竖线本身也有小圆角
      }
    }
  }
  .extend-info-modal-right {
    width: calc(100% - 185px);
    height: 100%;
    padding-left: 24px;
    padding-top: 20px;
    .extend-info-modal-right-title {
      font-size: 16px;
      font-weight: 500;
      color: useThemeVar('color_primary');
      margin-bottom: 24px;
    }
    .extend-info-modal-right-base {
      display: flex;
      flex-direction: column;
      height: calc(100% - 46px);
      overflow-y: auto;
      overflow-x: hidden;
      :deep(.el-form) {
        .el-form-item__label {
          color: useThemeVar('gray3');
          font-size: 14px;
        }
        .form-value-item {
          color: useThemeVar('gray1');
          font-size: 14px;
        }
      }
    }
    .extend-info-modal-right-role {
      height: calc(100% - 46px);
      .extend-info-modal-right-role-action {
        display: flex;
        justify-content: flex-end;
        margin-top: -24px;
        margin-bottom: 12px;
      }
    }
  }
}

// 1600px - 1920px 区间使用中等尺寸样式
@include screen-1600-to-1920 {
  :global(.el-dialog.responsive-dialog) {
    width: 992px;
    height: 560px !important;
  }
  :global(.el-dialog.responsive-add-user-dialog) {
    width: 992px;
    height: 580px;
  }
  .extend-info-modal {
    height: calc(560px - 46px);
  }
}

// 小于 1600px 使用小尺寸样式
@include screen-below-1600 {
  :global(.el-dialog.responsive-dialog) {
    width: 840px;
    height: 460px !important;
  }
  :global(.el-dialog.responsive-add-user-dialog) {
    width: 992px;
    height: 580px;
  }
  .extend-info-modal {
    height: calc(460px - 46px);
  }
}

.primary-button {
  background-color: var(--L_color_primary, #5483c7);
  color: var(--L_white1, #ffffff);

  &:hover {
    background-color: var(--L_primary_hover, #43699f);
    color: var(--L_white1, #ffffff);
  }
}

.gray-button {
  background-color: var(--L_button_gray_bg1, #f3f4f6);
  color: var(--L_gray1, #222222);

  &:hover {
    background-color: var(--L_button_gray_bg1, #e9ebf0);
    color: var(--L_gray1, #222222);
  }
}

:deep(.table-header) {
  font-weight: 500;
  color: #9e9e9e;
}

.page-data {
  display: flex;
  justify-content: flex-end;
  margin-top: 10px;
}
</style>
